package 分类.二分;

public class 在排序数组中查找元素的第一个和最后一个位置 {
    public static int[] searchRange1(int[] nums, int target) {
        return new int[]{leftround(nums,target),rightround(nums,target)};
    }

    static int leftround(int[] nums,int target){
        int left=0;
        int right=nums.length-1;
        while (left<=right){
            int mid=(left+right)/2;
            if(nums[mid]<target) left=mid+1;
            else if(nums[mid]>target) right=mid-1;
            else if(nums[mid]==target) right=mid-1;
        }
        if(left<0||left>=nums.length) return -1;
        if(nums[left]!=target) return -1;
        return left;
    }
    static int rightround(int[] nums,int target){
        int left=0;
        int right=nums.length-1;
        while (left<=right){
            int mid=(left+right)/2;
            if(nums[mid]<target) left=mid+1;
            else if(nums[mid]>target) right=mid-1;
            else if(nums[mid]==target)left=mid+1;
        }
        if(right==-1||nums[right]!=target) return -1;
        return right;
    }

    public static void main(String[] args) {
        int[] arr={0,0,1,2,3,3,4};
        System.out.println("leftround(arr,2) = " + leftround(arr, 2));


        /*for (int i : searchRange1(arr, 6)) {
            System.out.println(i);
        }*/
    }
}
